<?php

function stdfoot() {
	global $SITENAME, $BASEURL, $Cache, $datefounded, $tstart, $icplicense_main, $add_key_shortcut, $query_name, $USERUPDATESET, $CURUSER, $enablesqldebug_tweak, $sqldebug_tweak, $Advertisement, $analyticscode_tweak;
	global $lang_functions;
	print("</td></tr></table>");
	print("<div id=\"footer\">");
	$Advertisement = new ADVERTISEMENT($CURUSER['id']);
	if ($Advertisement->enable_ad()) {
		$footerad = $Advertisement->get_ad('footer');
		if ($footerad)
			echo "<div align=\"center\" style=\"margin-top: 10px\" id=\"ad_footer\">" . $footerad[0] . "</div>";
	}
	print("<div style=\"margin-top: 10px; margin-bottom: 30px;\" align=\"center\">");
	if ($CURUSER) {
		sql_query("UPDATE users SET " . join(", ", $USERUPDATESET) . " WHERE id = " . $CURUSER['id']);
	}
	// Variables for End Time
	//$tend = getmicrotime();
	//$totaltime = ($tend - $tstart);
	$year = substr($datefounded, 0, 4);
	$yearfounded = ($year ? $year : 2014);
	print(" (c) " . " <a href=\"" . get_protocol_prefix() . $BASEURL . "\" target=\"_self\">" . $SITENAME . "</a> " . ($icplicense_main ? " " . $icplicense_main . " " : "") . (date("Y") != $yearfounded ? $yearfounded . "-" : "") . date("Y") . " " . VERSION . "<br />");
	//print($lang_functions['text_about']);
	print($lang_functions['text_utdown']);
	//printf ("[page created in <b> %f </b> sec", $totaltime);
	//print (" with <b>".count($query_name)."</b> db queries, <b>".$Cache->getCacheReadTimes()."</b> reads and <b>".$Cache->getCacheWriteTimes()."</b> writes of memcached and <b>".mksize(memory_get_usage())."</b> ram]");
	print ("</div>\n");
	if ($enablesqldebug_tweak == 'yes' && get_user_class() >= $sqldebug_tweak) {
		print("<div id=\"sql_debug\">SQL query list: <ul>");
		foreach ($query_name as $query) {
			print("<li>" . htmlspecialchars($query) . "</li>");
		}
		print("</ul>");
		print("Memcached key read: <ul>");
		foreach ($Cache->getKeyHits('read') as $keyName => $hits) {
			print("<li>" . htmlspecialchars($keyName) . " : " . $hits . "</li>");
		}
		print("</ul>");
		print("Memcached key write: <ul>");
		foreach ($Cache->getKeyHits('write') as $keyName => $hits) {
			print("<li>" . htmlspecialchars($keyName) . " : " . $hits . "</li>");
		}
		print("</ul>");
		print("</div>");
	}
	print ("<div style=\"display: none;\" id=\"lightbox\" class=\"lightbox\"></div><div style=\"display: none;\" id=\"curtain\" class=\"curtain\"></div><div id=\"extraDiv1\"></div><div id=\"extraDiv2\"></div>");
	if ($add_key_shortcut != "")
		print($add_key_shortcut);
	print("</div>");
	/*
	  if ($CURUSER['danmu'] == 0) {
	  print("<iframe id=\"danmuku\" style=\"width: 99%; height: 200px; opacity: 0.9; position: fixed; bottom: 2px; z-index: 1000; visibility: hidden\" src=\"https://www.hdcn.info:3000/\" scrolling=\"no\" border=\"0\" frameborder=\"no\" allowtransparency=\"yes\" />");
	  }
	 * 弹幕库
	 */
	if ($analyticscode_tweak)
		print("\n" . $analyticscode_tweak . "\n");
	print("</body></html>");
	//echo replacePngTags(ob_get_clean());
	unset($_SESSION['queries']);
}

function deadtime() {
	global $anninterthree; //最长的汇报间隔
	return time() - floor($anninterthree + 60);
}

function mkprettytime($s) {
	global $lang_functions;
	if ($s < 0)
		$s = 0;
	$t = array();
	foreach (array("60:sec", "60:min", "24:hour", "0:day") as $x) {
		$y = explode(":", $x);
		if ($y[0] > 1) {
			$v = $s % $y[0];
			$s = floor($s / $y[0]);
		} else
			$v = $s;
		$t[$y[1]] = $v;
	}

	if ($t["day"])
		return $t["day"] . $lang_functions['text_day'] . sprintf("%02d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
	if ($t["hour"])
		return sprintf("%d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
//    if ($t["min"])
	return sprintf("%d:%02d", $t["min"], $t["sec"]);
//    return $t["sec"] . " secs";
}

function mkglobal($vars) {
	if (!is_array($vars))
		$vars = explode(":", $vars);
	foreach ($vars as $v) {
		if (isset($_GET[$v]))
			$GLOBALS[$v] = unesc($_GET[$v]);
		elseif (isset($_POST[$v]))
			$GLOBALS[$v] = unesc($_POST[$v]);
		else
			return 0;
	}
	return 1;
}

function tr($x, $y, $noesc = 0, $relation = '') {
	if ($noesc)
		$a = $y;
	else {
		$a = htmlspecialchars($y);
		$a = str_replace("\n", "<br />\n", $a);
	}
	print("<tr" . ( $relation ? " relation = \"$relation\"" : "") . "><td class=\"rowhead nowrap\" valign=\"top\" align=\"right\">$x</td><td class=\"rowfollow\" valign=\"top\" align=\"left\">" . $a . "</td></tr>\n");
}

function tr_small($x, $y, $noesc = 0, $relation = '') {
	if ($noesc)
		$a = $y;
	else {
		$a = htmlspecialchars($y);
//$a = str_replace("\n", "<br />\n", $a);
	}
	print("<tr" . ( $relation ? " relation = \"$relation\"" : "") . "><td width=\"1%\" class=\"rowhead nowrap\" valign=\"top\" align=\"right\">" . $x . "</td><td width=\"99%\" class=\"rowfollow\" valign=\"top\" align=\"left\">" . $a . "</td></tr>\n");
}

function twotd($x, $y, $nosec = 0) {
	if ($noesc)
		$a = $y;
	else {
		$a = htmlspecialchars($y);
		$a = str_replace("\n", "<br />\n", $a);
	}
	print("<td class=\"rowhead\">" . $x . "</td><td class=\"rowfollow\">" . $y . "</td>");
}

function validfilename($name) {
	return preg_match('/^[^\0-\x1f:\\\\\/?*\xff#<>|]+$/si', $name);
}

function validemail($email) {
	return preg_match('/^[\w.-]+@([\w.-]+\.)+[a-z]{2,6}$/is', $email);
}

function validlang($langid) {
	global $deflang;
	$langid = 0 + $langid;
	$res = sql_query("SELECT * FROM language WHERE site_lang = 1 AND id = " . sqlesc($langid)) or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) == 1) {
		$arr = mysql_fetch_array($res) or sqlerr(__FILE__, __LINE__);
		return $arr['site_lang_folder'];
	} else
		return $deflang;
}

function get_if_restricted_is_open() {
	global $sptime;
// it's sunday
	if ($sptime == 'yes' && (date("w", time()) == '0' || (date("w", time()) == 6) && (date("G", time()) >= 12 && date("G", time()) <= 23))) {
		return true;
	} else
		return false;
}

function get_css_row() {
	global $CURUSER, $defcss, $Cache;
	static $rows;
	$cssid = $CURUSER ? $CURUSER["stylesheet"] : $defcss;
	if (!$rows && !$rows = $Cache->get_value('stylesheet_content')) {
		$rows = array();
		$res = sql_query("SELECT * FROM stylesheets ORDER BY id ASC");
		while ($row = mysql_fetch_array($res)) {
			$rows[$row['id']] = $row;
		}
		$Cache->cache_value('stylesheet_content', $rows, 2592000);
	}
	return $rows[$cssid];
}

function get_css_uri($file = "") {
	global $defcss;
	$cssRow = get_css_row();
	$ss_uri = $cssRow['uri'];
	if (!$ss_uri)
		$ss_uri = get_single_value("stylesheets", "uri", "WHERE id=" . sqlesc($defcss));
	if ($file == "")
		return $ss_uri;
	else
		return $ss_uri . $file;
}

function get_font_css_uri() {
	global $CURUSER;
	if ($CURUSER['fontsize'] == 'large')
		$file = 'largefont.css';
	elseif ($CURUSER['fontsize'] == 'small')
		$file = 'smallfont.css';
	else
		$file = 'mediumfont.css';
	return "styles/" . $file;
}

function get_style_addicode() {
	$cssRow = get_css_row();
	return $cssRow['addicode'];
}

function get_cat_folder($cat = 101) {
	static $catPath = array();
	if (!$catPath[$cat]) {
		global $CURUSER, $CURLANGDIR;
		$catrow = get_category_row($cat);
		$catmode = $catrow['catmodename'];
		$caticonrow = get_category_icon_row($CURUSER['caticon']);
		$catPath[$cat] = "category/" . $catmode . "/" . $caticonrow['folder'] . ($caticonrow['multilang'] == 'yes' ? $CURLANGDIR . "/" : "");
	}
	return $catPath[$cat];
}

function genbark($x, $y) {
	stdhead($y);
	print("<h1>" . htmlspecialchars($y) . "</h1>\n");
	print("<p>" . htmlspecialchars($x) . "</p>\n");
	stdfoot();
	exit();
}

function mksecret($len = 20) {
	$ret = "";
	for ($i = 0; $i < $len; $i++)
		$ret .= chr(mt_rand(100, 120));
	return $ret;
}

function httperr($code = 404) {
	header("HTTP/1.1 $code Not found");
	print("<h1>Not Found</h1>\n");
	exit();
}

function logincookie($id, $passhash, $updatedb = 1, $expires = 0x7fffffff, $securelogin = false, $ssl = false, $trackerssl = false) {
	if ($expires != 0x7fffffff)
		$expires = time() + $expires;

	setcookie("c_secure_uid", base64($id), $expires, "/");
	setcookie("c_secure_pass", $passhash, $expires, "/");
	if ($ssl)
		setcookie("c_secure_ssl", base64("yeah"), $expires, "/");
	else
		setcookie("c_secure_ssl", base64("nope"), $expires, "/");

	if ($trackerssl)
		setcookie("c_secure_tracker_ssl", base64("yeah"), $expires, "/");
	else
		setcookie("c_secure_tracker_ssl", base64("nope"), $expires, "/");

	if ($securelogin)
		setcookie("c_secure_login", base64("yeah"), $expires, "/");
	else
		setcookie("c_secure_login", base64("nope"), $expires, "/");

	if ($updatedb)
		sql_query("UPDATE users SET last_login = NOW(), lang=" . sqlesc(get_langid_from_langcookie()) . " WHERE id = " . sqlesc($id));
}

function set_langfolder_cookie($folder, $expires = 0x7fffffff) {
	if ($expires != 0x7fffffff)
		$expires = time() + $expires;

	setcookie("c_lang_folder", $folder, $expires, "/");
}

function get_protocol_prefix() {
	global $securelogin;
	if ($securelogin == "yes") {
		return "https://";
	} elseif ($securelogin == "no") {
		return "http://";
	} else {
		if (!isset($_COOKIE["c_secure_ssl"])) {
			return "http://";
		} else {
			return base64_decode($_COOKIE["c_secure_ssl"]) == "yeah" ? "https://" : "http://";
		}
	}
}

function get_langid_from_langcookie() {
	global $CURLANGDIR;
	$row = mysql_fetch_array(sql_query("SELECT id FROM language WHERE site_lang = 1 AND site_lang_folder = " . sqlesc($CURLANGDIR) . "ORDER BY id ASC")) or sqlerr(__FILE__, __LINE__);
	return $row['id'];
}

function make_folder($pre, $folder_name) {
	$path = $pre . $folder_name;
	if (!file_exists($path))
		mkdir($path, 0777, true);
	return $path;
}

function logoutcookie() {
	setcookie("c_secure_uid", "", 0x7fffffff, "/");
	setcookie("c_secure_pass", "", 0x7fffffff, "/");
	//setcookie("c_secure_ssl", "", 0x7fffffff, "/");
	setcookie("c_secure_tracker_ssl", "", 0x7fffffff, "/");
	setcookie("c_secure_login", "", 0x7fffffff, "/");
	//setcookie("c_lang_folder", "", 0x7fffffff, "/");
}

function base64($string, $encode = true) {
	if ($encode)
		return base64_encode($string);
	else
		return base64_decode($string);
}

function loggedinorreturn($mainpage = false) {
	global $CURUSER, $BASEURL, $authoff;
	if (!$CURUSER) {
		if ($mainpage) {
			if ($authoff == 'yes') {
				header("Location: " . get_protocol_prefix() . "$BASEURL/auth.php");
			} else {
				header("Location: " . get_protocol_prefix() . "$BASEURL/login.php");
			}
		} else {
			$to = basename($_SERVER["REQUEST_URI"]);
			if ($authoff == 'yes') {
				header("Location: " . get_protocol_prefix() . "$BASEURL/auth.php?returnto=" . rawurlencode($to));
			} else {
				header("Location: " . get_protocol_prefix() . "$BASEURL/login.php?returnto=" . rawurlencode($to));
			}
		}
		exit();
	}
}

function deletetorrent($id, $url, $dburl) {
	global $torrent_dir, $rootpath;
	sql_query("DELETE FROM torrents WHERE id = " . mysql_real_escape_string($id));
	sql_query("DELETE FROM snatched WHERE torrentid = " . mysql_real_escape_string($id));
	foreach (array("peers", "files", "comments") as $x) {
		sql_query("DELETE FROM $x WHERE torrent = " . mysql_real_escape_string($id));
	}
	unlink($rootpath . "$torrent_dir/$id.torrent");
	unlink($rootpath . "imdb/cache/$url.Title");
	unlink($rootpath . "imdb/images/$url.jpg");
	unlink($rootpath . "imdb/cache/$dburl.page");
	unlink($rootpath . "imdb/images/$dburl.jpg");
}

function pager($rpp, $count, $href, $opts = array(), $pagename = "page", $status = "") {
	global $lang_functions, $add_key_shortcut;
	$pages = ceil($count / $rpp);
	$status = $_GET['status'];
	if (!$opts["lastpagedefault"])
		$pagedefault = 0;
	else {
		$pagedefault = floor(($count - 1) / $rpp);
		if ($pagedefault < 0)
			$pagedefault = 0;
	}

	if (isset($_GET[$pagename])) {
		$page = 0 + $_GET[$pagename];
		if ($page < 0)
			$page = $pagedefault;
	} else
		$page = $pagedefault;

	$pager = "";
	$mp = $pages - 1;

	//Opera (Presto) doesn't know about event.altKey
	$is_presto = strpos($_SERVER['HTTP_USER_AGENT'], 'Presto');
	$as = "<b title=\"" . ($is_presto ? $lang_functions['text_shift_pageup_shortcut'] : $lang_functions['text_alt_pageup_shortcut']) . "\">&lt;&lt;&nbsp;" . $lang_functions['text_prev'] . "</b>";
	if ($page >= 1) {
		$pager .= "<a href=\"" . htmlspecialchars($href . ($status != '' ? "status=" . $status . "&" : "") . $pagename . "=" . ($page - 1)) . "\">";
		$pager .= $as;
		$pager .= "</a>";
	} else
		$pager .= "<font class=\"gray\">" . $as . "</font>";
	$pager .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	$as = "<b title=\"" . ($is_presto ? $lang_functions['text_shift_pagedown_shortcut'] : $lang_functions['text_alt_pagedown_shortcut']) . "\">" . $lang_functions['text_next'] . "&nbsp;&gt;&gt;</b>";
	if ($page < $mp && $mp >= 0) {
		$pager .= "<a href=\"" . htmlspecialchars($href . ($status != '' ? "status=" . $status . "&" : "") . $pagename . "=" . ($page + 1)) . "\">";
		$pager .= $as;
		$pager .= "</a>";
	} else
		$pager .= "<font class=\"gray\">" . $as . "</font>";

	if ($count) {
		$pagerarr = array();
		$dotted = 0;
		$dotspace = 3;
		$dotend = $pages - $dotspace;
		$curdotend = $page - $dotspace;
		$curdotstart = $page + $dotspace;
		for ($i = 0; $i < $pages; $i++) {
			if (($i >= $dotspace && $i <= $curdotend) || ($i >= $curdotstart && $i < $dotend)) {
				if (!$dotted)
					$pagerarr[] = "...";
				$dotted = 1;
				continue;
			}
			$dotted = 0;
			$start = $i * $rpp + 1;
			$end = $start + $rpp - 1;
			if ($end > $count)
				$end = $count;
			$text = "$start&nbsp;-&nbsp;$end";
			//	$text = "".ceil($end/$rpp);
			if ($i != $page)
				$pagerarr[] = "<a href=\"" . htmlspecialchars($href . ($status != '' ? "status=" . $status . "&" : "") . $pagename . "=" . $i) . "\"><b>$text</b></a>";
			else
				$pagerarr[] = "<font class=\"gray\"><b>$text</b></font>";
		}
		$pagerstr = join(" | ", $pagerarr);
		$pagertop = "<p align=\"center\">$pager<br />$pagerstr</p>\n";
		$pagerbottom = "<p align=\"center\">$pagerstr<br />$pager</p>\n";
	}
	else {
		$pagertop = "<p align=\"center\">$pager</p>\n";
		$pagerbottom = $pagertop;
	}

	$start = $page * $rpp;
	$add_key_shortcut = key_shortcut($page, $pages - 1);
	return array("<font size=2>" . $pagertop . "</font>", "<font size=2>" . $pagerbottom . "</font>", "LIMIT $start,$rpp");
}

function commenttable($rows, $type, $parent_id, $review = false) {
	global $lang_functions;
	global $CURUSER, $commanage_class;
	global $Advertisement;
	begin_main_frame();
	begin_frame();

	$count = 0;
	if ($Advertisement->enable_ad())
		$commentad = $Advertisement->get_ad('comment');
	foreach ($rows as $row) {
		$userRow = get_user_row($row['user']);
		if ($count >= 1) {
			if ($Advertisement->enable_ad()) {
				if ($commentad[$count - 1])
					echo "<div align=\"center\" style=\"margin-top: 10px\" id=\"ad_comment_" . $count . "\">" . $commentad[$count - 1] . "</div>";
			}
		}
		print("<div style=\"margin-top: 8pt; margin-bottom: 8pt;\"><table id=\"cid" . $row["id"] . "\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\"><tr><td class=\"embedded\" width=\"99%\"><a href=$_SERVER[REQUEST_URI]#cid$row[id]>#" . $row["id"] . "</a>&nbsp;&nbsp;<font color=\"gray\">" . $lang_functions['text_by'] . "</font>");
		print(get_username($row["user"], false, true, true, false, false, true));
		print("&nbsp;&nbsp;<font color=\"gray\">" . $lang_functions['text_at'] . "</font>" . gettime($row["added"]) .
				($row["editedby"] && get_user_class() >= $commanage_class ? " - [<a href=\"comment.php?action=vieworiginal&amp;cid=" . $row[id] . "&amp;type=" . $type . "\">" . $lang_functions['text_view_original'] . "</a>]" : "") . "</td><td class=\"embedded nowrap\" width=\"1%\"><a href=\"#top\"><img class=\"top\" src=\"pic/trans.gif\" alt=\"Top\" title=\"Top\" /></a>&nbsp;&nbsp;</td></tr></table></div>");
		$avatar = ($CURUSER["avatars"] == "yes" ? htmlspecialchars(trim($userRow["avatar"])) : "");
		if (!$avatar)
			$avatar = "pic/default_avatar.png";
		$text = format_comment($row["text"]);
		$text_editby = "";
		if ($row["editedby"]) {
			$lastedittime = gettime($row['editdate'], true, false);
			$text_editby = "<br /><p><font class=\"small\">" . $lang_functions['text_last_edited_by'] . get_username($row['editedby']) . $lang_functions['text_edited_at'] . $lastedittime . "</font></p>\n";
		}

		print("<table class=\"main\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\">\n");
		$secs = 900;
		$dt = sqlesc(date("Y-m-d H:i:s", (TIMENOW - $secs))); // calculate date.
		print("<tr>\n");
		print("<td class=\"rowfollow\" width=\"150\" valign=\"top\" style=\"padding: 0px;\">" . return_avatar_image($avatar) . "</td>\n");
		print("<td class=\"rowfollow\" valign=\"top\"><br />" . $text . $text_editby . "</td>\n");
		print("</tr>\n");
		$actionbar = "<a href=\"#replaytext\" onClick=\"javascript:quick_reply_to('回复[@" . get_username($row["user"], false, true, true, false, false, true, 1, 1, 1) . "]');\"><img class=\"f_reply\" src=\"pic/trans.gif\" alt=\"Add Reply\" title=\"回复\" /></a>" .
				"<a href=\"comment.php?action=add&amp;sub=quote&amp;cid=" . $row[id] . "&amp;pid=" . $parent_id . "&amp;type=" . $type . "\"><img class=\"f_quote\" src=\"pic/trans.gif\" alt=\"Quote\" title=\"" . $lang_functions['title_reply_with_quote'] . "\" /></a>" .
				(get_user_class() >= $commanage_class ? "<a href=\"comment.php?action=delete&amp;cid=" . $row[id] . "&amp;type=" . $type . "\"><img class=\"f_delete\" src=\"pic/trans.gif\" alt=\"Delete\" title=\"" . $lang_functions['title_delete'] . "\" /></a>" : "") . ($row["user"] == $CURUSER["id"] || get_user_class() >= $commanage_class ? "<a href=\"comment.php?action=edit&amp;cid=" . $row[id] . "&amp;type=" . $type . "\"><img class=\"f_edit\" src=\"pic/trans.gif\" alt=\"Edit\" title=\"" . $lang_functions['title_edit'] . "\" />" . "</a>" : "");
		print("<tr><td class=\"toolbox\"> " . ("'" . $userRow['last_access'] . "'" > $dt && $userRow['class'] != UC_STAFFLEADER ? "<img class=\"f_online\" src=\"pic/trans.gif\" alt=\"Online\" title=\"" . $lang_functions['title_online'] . "\" />" : "<img class=\"f_offline\" src=\"pic/trans.gif\" alt=\"Offline\" title=\"" . $lang_functions['title_offline'] . "\" />" ) . "<a href=\"sendmessage.php?receiver=" . htmlspecialchars(trim($row["user"])) . "\"><img class=\"f_pm\" src=\"pic/trans.gif\" alt=\"PM\" title=\"" . $lang_functions['title_send_message_to'] . htmlspecialchars($userRow["username"]) . "\" /></a><a href=\"report.php?commentid=" . htmlspecialchars(trim($row["id"])) . "\"><img class=\"f_report\" src=\"pic/trans.gif\" alt=\"Report\" title=\"" . $lang_functions['title_report_this_comment'] . "\" /></a></td><td class=\"toolbox\" align=\"right\">" . $actionbar . "</td>");

		print("</tr></table>\n");
		$count++;
	}
	end_frame();
	end_main_frame();
}

function searchfield($s) {
	return preg_replace(array('/[^a-z0-9]/si', '/^\s*/s', '/\s*$/s', '/\s+/s'), array(" ", "", "", " "), $s);
}

function genrelist($catmode = 1) {
	global $Cache, $limitsecurity, $onsecurity;
	if (!$ret = $Cache->get_value('category_list_mode_' . $catmode)) {
		$ret = array();
		if ($limitsecurity == 'yes' && get_user_class() < UC_ADMINISTRATOR) {
			$res = sql_query("SELECT id, mode, name, image FROM categories WHERE id < '424' AND mode = " . sqlesc($catmode) . " ORDER BY sort_index, id");
		} elseif ($onsecurity == 'yes' && get_user_class() < UC_ADMINISTRATOR) {
			$res = sql_query("SELECT id, mode, name, image FROM categories WHERE id < '424' AND mode = " . sqlesc($catmode) . " ORDER BY sort_index, id");
		} else {
			$res = sql_query("SELECT id, mode, name, image FROM categories WHERE mode = " . sqlesc($catmode) . " ORDER BY sort_index, id");
		}
		while ($row = mysql_fetch_array($res))
			$ret[] = $row;
		//$Cache->cache_value('category_list_mode_' . $catmode, $ret, 152800);
	}
	return $ret;
}

function genrelistnolimit($catmode = 1) {
	global $Cache;
	if (!$ret = $Cache->get_value('category_list_nolimit_mode_' . $catmode)) {
		$ret = array();
		$res = sql_query("SELECT id, mode, name, image FROM categories WHERE id != '424' AND mode = " . sqlesc($catmode) . " ORDER BY sort_index, id");
		while ($row = mysql_fetch_array($res))
			$ret[] = $row;
		$Cache->cache_value('category_list_nolimit_mode_' . $catmode, $ret, 152800);
	}
	return $ret;
}

function genrelistlimit($catmode = 1) {
	global $Cache;
	if (!$ret = $Cache->get_value('category_list_limit_mode_' . $catmode)) {
		$ret = array();
		$res = sql_query("SELECT id, mode, name, image FROM categories WHERE id >= '424' AND mode = " . sqlesc($catmode) . " ORDER BY sort_index, id");
		while ($row = mysql_fetch_array($res))
			$ret[] = $row;
		$Cache->cache_value('category_list_limit_mode_' . $catmode, $ret, 152800);
	}
	return $ret;
}

function searchbox_item_list($table = "sources", $lid = 0) {
	global $Cache;
	if (!$ret = $Cache->get_value($table . '_list_' . $lid)) {
		$ret = array();
		if ($lid == 0)
			$res = sql_query("SELECT * FROM " . $table . " ORDER BY lid, sort_index, id");
		else
			$res = sql_query("SELECT * FROM " . $table . " WHERE lid='" . $lid . "' ORDER BY lid, sort_index, id");
		while ($row = mysql_fetch_array($res))
			$ret[] = $row;
		$Cache->cache_value($table . '_list_' . $lid, $ret, 152800);
	}
	return $ret;
}

function langlist($type) {
	global $Cache;
	if (!$ret = $Cache->get_value($type . '_lang_list')) {
		$ret = array();
		$res = sql_query("SELECT id, lang_name, flagpic, site_lang_folder FROM language WHERE " . $type . "=1 ORDER BY site_lang DESC, id ASC");
		while ($row = mysql_fetch_array($res))
			$ret[] = $row;
		$Cache->cache_value($type . '_lang_list', $ret, 152800);
	}
	return $ret;
}

function linkcolor($num) {
	if (!$num)
		return "red";
	//    if ($num == 1)
	//        return "yellow";
	return "green";
}

function writecomment($userid, $comment) {
	$res = sql_query("SELECT modcomment FROM users WHERE id = '$userid'") or sqlerr(__FILE__, __LINE__);
	$arr = mysql_fetch_assoc($res);

	$modcomment = date("Y-m-d") . " - " . $comment . "" . ($arr[modcomment] != "" ? "\n" : "") . "$arr[modcomment]";
	$modcom = sqlesc($modcomment);

	return sql_query("UPDATE users SET modcomment = $modcom WHERE id = '$userid'") or sqlerr(__FILE__, __LINE__);
}

function return_torrent_bookmark_array($userid) {
	global $Cache;
	static $ret;
	if (!$ret) {
		if (!$ret = $Cache->get_value('user_' . $userid . '_bookmark_array')) {
			$ret = array();
			$res = sql_query("SELECT * FROM bookmarks WHERE userid=" . sqlesc($userid));
			if (mysql_num_rows($res) != 0) {
				while ($row = mysql_fetch_array($res))
					$ret[] = $row['torrentid'];
				$Cache->cache_value('user_' . $userid . '_bookmark_array', $ret, 259200);
			} else {
				$Cache->cache_value('user_' . $userid . '_bookmark_array', array(0), 259200);
			}
		}
	}
	return $ret;
}

function get_torrent_bookmark_state($userid, $torrentid, $text = false) {
	global $lang_functions;
	$userid = 0 + $userid;
	$torrentid = 0 + $torrentid;
	$ret = array();
	$ret = return_torrent_bookmark_array($userid);
	if (!count($ret) || !in_array($torrentid, $ret, false)) // already bookmarked
		$act = ($text == true ? $lang_functions['title_bookmark_torrent'] : "<img class=\"delbookmark\" src=\"pic/trans.gif\" alt=\"Unbookmarked\" title=\"" . $lang_functions['title_bookmark_torrent'] . "\" />");
	else
		$act = ($text == true ? $lang_functions['title_delbookmark_torrent'] : "<img class=\"bookmark\" src=\"pic/trans.gif\" alt=\"Bookmarked\" title=\"" . $lang_functions['title_delbookmark_torrent'] . "\" />");
	return $act;
}

function return_torrent_album_array($userid) {
	global $Cache;
	static $ret;
	if (!$ret) {
		if (!$ret = $Cache->get_value('user_' . $userid . '_album_array')) {
			$ret = array();
			$res = sql_query("SELECT * FROM albumfav WHERE userid=" . sqlesc($userid));
			if (mysql_num_rows($res) != 0) {
				while ($row = mysql_fetch_array($res))
					$ret[] = $row['id'];
				$Cache->cache_value('user_' . $userid . '_album_array', $ret, 259200);
			} else {
				$Cache->cache_value('user_' . $userid . '_album_array', array(0), 259200);
			}
		}
	}
	return $ret;
}

function get_torrent_album_state($userid, $albumid, $text = false) {
	global $lang_functions;
	$userid = 0 + $userid;
	$albumid = 0 + $albumid;
	$ret = array();
	$ret = return_torrent_album_array($userid);
	if (!count($ret) || !in_array($albumid, $ret, false)) // already bookmarked
		$act = ($text == true ? $lang_functions['title_bookmark_torrent'] : "<img class=\"delbookmark\" src=\"pic/trans.gif\" alt=\"Unbookmarked\" title=\"" . $lang_functions['title_bookmark_torrent'] . "\" />");
	else
		$act = ($text == true ? $lang_functions['title_delbookmark_torrent'] : "<img class=\"bookmark\" src=\"pic/trans.gif\" alt=\"Bookmarked\" title=\"" . $lang_functions['title_delbookmark_torrent'] . "\" />");
	return $act;
}

function return_torrent_truckmark_array($userid) {
	global $Cache;
	static $ret;
	if (!$ret) {
		if (!$ret = $Cache->get_value('user_' . $userid . '_truckmark_array')) {
			$ret = array();
			$res = sql_query("SELECT * FROM truckmarks WHERE userid=" . sqlesc($userid));
			if (mysql_num_rows($res) != 0) {
				while ($row = mysql_fetch_array($res))
					$ret[] = $row['torrentid'];
				$Cache->cache_value('user_' . $userid . '_truckmark_array', $ret, 259200);
			} else {
				$Cache->cache_value('user_' . $userid . '_truckmark_array', array(0), 259200);
			}
		}
	}
	return $ret;
}

function get_torrent_truckmark_state($userid, $torrentid, $text = false) {
	$userid = 0 + $userid;
	$torrentid = 0 + $torrentid;
	$ret = array();
	$ret = return_torrent_truckmark_array($userid);
	if (!count($ret) || !in_array($torrentid, $ret, false)) // already truckmarked
		$act = ($text == true ? "放进小货车" : "<img class=\"truckmark\" src=\"pic/trans.gif\" alt=\"Untruckmarked\" title=\"放进小货车\" />");
	else
		$act = ($text == true ? "移出小货车" : "<img class=\"truckmark\" src=\"pic/trans.gif\" alt=\"Truckmarked\" title=\"移出小货车\" />");
	return $act;
}

function get_torrent_pushfree_state($userid, $torrentid, $text = false) {
	$userid = 0 + $userid;
	$torrentid = 0 + $torrentid;
	$res = sql_query("SELECT * FROM blue WHERE torrentid = $torrentid AND userid = $userid") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) != 1) // already pushfree
		$act = ($text == true ? "我要投蓝" : "<input type=\"button\" name=\"button\" value=\"我要投蓝\" />");
	else
		$act = ($text == true ? "感谢投篮" : "<input type=\"button\" name=\"button\" value=\"感谢投蓝\" disabled=\"disabled\" />");
	return $act;
}

function get_torrent_claim_state($userid, $torrentid, $text = false) {
	global $claimmaxnum, $claimnum;
	$userid = 0 + $userid;
	$torrentid = 0 + $torrentid;
	$res1 = sql_query("SELECT id FROM claim WHERE torrentid = $torrentid") or sqlerr(__FILE__, __LINE__);
	$res2 = sql_query("SELECT id FROM claim WHERE torrentid = $torrentid AND userid = $userid") or sqlerr(__FILE__, __LINE__);
	$res3 = sql_query("SELECT id FROM claim WHERE userid = $userid") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res2) != 1 && mysql_num_rows($res3) < $claimnum) {// already pushfree
		$act = ($text == true ? "认领种子" : "<input type=\"button\" name=\"button\" value=\"认领种子\" />");
	} elseif (mysql_num_rows($res1) >= $claimmaxnum) {
		$act = ($text == true ? "已到单种最大认领数" : "<input type=\"button\" name=\"button\" value=\"已到单种最大认领数\" disabled=\"disabled\" />");
	} elseif (mysql_num_rows($res3) >= $claimnum) {
		$act = ($text == true ? "您认领的种子已经达到最大数量！" : "<input type=\"button\" name=\"button\" value=\"您可认领的种子已经达到最大数量！\" disabled=\"disabled\" />");
	} else {
		$act = ($text == true ? "已经认领" : "<input type=\"button\" name=\"button\" value=\"已经认领\" disabled=\"disabled\" />");
	}
	return $act;
}

function get_torrent_claimtor_state($userid, $torrentid, $text = false) {
	$userid = 0 + $userid;
	$torrentid = 0 + $torrentid;
	$res = sql_query("SELECT id FROM claim WHERE torrentid = $torrentid") or sqlerr(__FILE__, __LINE__);
	$claimtotal = mysql_num_rows($res);
	if ($claimtotal > 0)
		$act = ($text == true ? $claimtotal : "<img class=\"claim\" src=\"pic/trans.gif\" alt=\"claim\" title=\"认领人数：" . $claimtotal . "\" />");
	return $act;
}

function get_username($id, $big = false, $link = true, $bold = true, $target = false, $bracket = false, $withtitle = false, $link_ext = "", $underline = false, $onlyname = false) {
	static $usernameArray = array();
	global $lang_functions;
	$id = 0 + $id;

	if (func_num_args() == 1 && $usernameArray[$id]) {  //One argument=is default display of username. Get it directly from static array if available
		return $usernameArray[$id];
	}
	$row = mysql_num_rows(sql_query("SELECT id FROM users WHERE id = $id"));
	if ($row == 1) {
		$arr = get_user_row($id);
		if ($onlyname) {
			return $arr['username'];
		}
		if ($big) {
			$donorpic = "starbig";
			$leechwarnpic = "leechwarnedbig";
			$warnedpic = "warnedbig";
			$disabledpic = "disabledbig";
			$style = "style='margin-left: 4pt'";
		} else {
			$donorpic = "star";
			$leechwarnpic = "leechwarned";
			$warnedpic = "warned";
			$disabledpic = "disabled";
			$style = "style='margin-left: 2pt'";
		}
		$pics = $arr["donor"] == "yes" ? "<img class=\"" . $donorpic . "\" src=\"pic/trans.gif\" alt=\"Donor\" " . $style . " />" : "";

		if ($arr["enabled"] == "yes") {
			$pics .= ($arr["leechwarn"] == "yes" ? "<img class=\"" . $leechwarnpic . "\" src=\"pic/trans.gif\" alt=\"Leechwarned\" " . $style . " />" : "") . ($arr["warned"] == "yes" ? "<img class=\"" . $warnedpic . "\" src=\"pic/trans.gif\" alt=\"Warned\" " . $style . " />" : "");
			$username = ($underline == true ? $arr['username'] : $arr['username']);
			$username = ($bold == true ? "<b>" . $username . "</b>" : $username);
			$username = ($link == true ? "<a " . $link_ext . " href=\"userdetails.php?id=" . $id . "\"" . ($target == true ? " target=\"_blank\"" : "") . " class='" . get_user_class_name($arr['class'], true) . "_Name'>" . $username . "</a>" : $username) . $pics . ($withtitle == true ? " (" . ($arr['title'] == "" ? get_user_class_name($arr['class'], false, true, true) : "<span class='" . get_user_class_name($arr['class'], true) . "_Name'><b>" . htmlspecialchars($arr['title'])) . "</b></span>)" : "");
			$username = "<span class=\"nowrap\">" . ( $bracket == true ? "(" . $username . ")" : $username) . "</span>";
		} else {
			$username = ($underline == true ? $arr['username'] : $arr['username']);
			$username = ($bold == true ? "<b>" . $username . "</b>" : $username);
			$username = ($link == true ? "<a " . $link_ext . " href=\"userdetails.php?id=" . $id . "\"" . ($target == true ? " target=\"_blank\"" : "") . " class='" . get_user_class_name($arr['class'], true) . "_Name'>" . $username . "</a>" : $username) . $pics . ($withtitle == true ? " (" . ($arr['title'] == "" ? get_user_class_name($arr['class'], false, true, true) : "<span class='" . get_user_class_name($arr['class'], true) . "_Name'><b>" . htmlspecialchars($arr['title'])) . "</b></span>)" : "");
			$username = "<span class=\"nowrap\">" . ( $bracket == true ? "(" . $username . ")" : $username) . "</span>";
			$pics .= "<img class=\"" . $disabledpic . "\" src=\"pic/trans.gif\" title=\"禁用\" alt=\"禁用\" " . $style . " />\n";
			$username = ($link == true ? $username . $pics : "");
		}
	} else {
		$username = "<i>" . $lang_functions['text_orphaned'] . "</i>";
		$username = "<span class=\"nowrap\">" . ( $bracket == true ? "(" . $username . ")" : $username) . "</span>";
	}
	if (func_num_args() == 1) { //One argument=is default display of username, save it in static array
		$usernameArray[$id] = $username;
	}
	return $username;
}

function get_percent_completed_image($p) {
	$maxpx = "45"; // Maximum amount of pixels for the progress bar

	if ($p == 0)
		$progress = "<img class=\"progbarrest\" src=\"pic/trans.gif\" style=\"width: " . ($maxpx) . "px;\" alt=\"\" />";
	if ($p == 100)
		$progress = "<img class=\"progbargreen\" src=\"pic/trans.gif\" style=\"width: " . ($maxpx) . "px;\" alt=\"\" />";
	if ($p >= 1 && $p <= 30)
		$progress = "<img class=\"progbarred\" src=\"pic/trans.gif\" style=\"width: " . ($p * ($maxpx / 100)) . "px;\" alt=\"\" /><img class=\"progbarrest\" src=\"pic/trans.gif\" style=\"width: " . ((100 - $p) * ($maxpx / 100)) . "px;\" alt=\"\" />";
	if ($p >= 31 && $p <= 65)
		$progress = "<img class=\"progbaryellow\" src=\"pic/trans.gif\" style=\"width: " . ($p * ($maxpx / 100)) . "px;\" alt=\"\" /><img class=\"progbarrest\" src=\"pic/trans.gif\" style=\"width: " . ((100 - $p) * ($maxpx / 100)) . "px;\" alt=\"\" />";
	if ($p >= 66 && $p <= 99)
		$progress = "<img class=\"progbargreen\" src=\"pic/trans.gif\" style=\"width: " . ($p * ($maxpx / 100)) . "px;\" alt=\"\" /><img class=\"progbarrest\" src=\"pic/trans.gif\" style=\"width: " . ((100 - $p) * ($maxpx / 100)) . "px;\" alt=\"\" />";
	return "<img class=\"bar_left\" src=\"pic/trans.gif\" alt=\"\" />" . $progress . "<img class=\"bar_right\" src=\"pic/trans.gif\" alt=\"\" />";
}

function get_ratio_img($ratio) {
	if ($ratio >= 16)
		$s = "55";
	elseif ($ratio >= 8)
		$s = "7";
	elseif ($ratio >= 4)
		$s = "27";
	elseif ($ratio >= 2)
		$s = "31";
	elseif ($ratio >= 1)
		$s = "39";
	elseif ($ratio >= 0.5)
		$s = "62";
	elseif ($ratio >= 0.25)
		$s = "74";
	else
		$s = "60";

	return "<img style=\"width:64px;height:64px;padding-bottom:auto;\" src=\"pic/smilies/" . $s . ".png\" alt=\"\" />";
}

function GetVar($name) {
	if (is_array($name)) {
		foreach ($name as $var)
			GetVar($var);
	} else {
		if (!isset($_REQUEST[$name]))
			return false;
		if (get_magic_quotes_gpc()) {
			$_REQUEST[$name] = ssr($_REQUEST[$name]);
		}
		$GLOBALS[$name] = $_REQUEST[$name];
		return $GLOBALS[$name];
	}
}

function ssr($arg) {
	if (is_array($arg)) {
		foreach ($arg as $key => $arg_bit) {
			$arg[$key] = ssr($arg_bit);
		}
	} else {
		$arg = stripslashes($arg);
	}
	return $arg;
}

function parked() {
	global $lang_functions;
	global $CURUSER;
	if ($CURUSER["parked"] == "yes")
		stderr($lang_functions['std_access_denied'], $lang_functions['std_your_account_parked']);
}

function utf8_strlen($str = null) {
//return (strlen($str)+mb_strlen($str,'utf-8'))/2; //开启了php_mbstring.dll扩展
	$name_len = strlen($str);
	$temp_len = 0;
	for ($i = 0; $i < $name_len;
	) {
		if (strpos('@._-=+[]() {

									}\\\/<>!#$%^&*~`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstvuwxyz0123456789', $str [$i]) === false) {
			$i = $i + 3;
			$temp_len += 2;
		} else {
			$i = $i + 1;
			$temp_len += 1;
		}
	}
	return $temp_len;
//preg_match_all("/./us", $string, $match);
//return count($match[0]);
}

function validusername($username) {
	if ($username == "")
		return false;

	// The following characters are allowed in user names
	$allowedchars = "/^([\x{4e00}-\x{9fa5}A-Za-z0-9]*$)/u";
	if (preg_match($allowedchars, $username))
		return true;

	return false;
}

//Code for Viewing NFO file
// code: Takes a string and does a IBM-437-to-HTML-Unicode-Entities-conversion.
// swedishmagic specifies special behavior for Swedish characters.
// Some Swedish Latin-1 letters collide with popular DOS glyphs. If these
// characters are between ASCII-characters (a-zA-Z and more) they are
// treated like the Swedish letters, otherwise like the DOS glyphs.
function code($ibm_437, $swedishmagic = false) {
	$table437 = array("\200", "\201", "\202", "\203", "\204", "\205", "\206", "\207",
		"\210", "\211", "\212", "\213", "\214", "\215", "\216", "\217", "\220",
		"\221", "\222", "\223", "\224", "\225", "\226", "\227", "\230", "\231",
		"\232", "\233", "\234", "\235", "\236", "\237", "\240", "\241", "\242",
		"\243", "\244", "\245", "\246", "\247", "\250", "\251", "\252", "\253",
		"\254", "\255", "\256", "\257", "\260", "\261", "\262", "\263", "\264",
		"\265", "\266", "\267", "\270", "\271", "\272", "\273", "\274", "\275",
		"\276", "\277", "\300", "\301", "\302", "\303", "\304", "\305", "\306",
		"\307", "\310", "\311", "\312", "\313", "\314", "\315", "\316", "\317",
		"\320", "\321", "\322", "\323", "\324", "\325", "\326", "\327", "\330",
		"\331", "\332", "\333", "\334", "\335", "\336", "\337", "\340", "\341",
		"\342", "\343", "\344", "\345", "\346", "\347", "\350", "\351", "\352",
		"\353", "\354", "\355", "\356", "\357", "\360", "\361", "\362", "\363",
		"\364", "\365", "\366", "\367", "\370", "\371", "\372", "\373", "\374",
		"\375", "\376", "\377");

	$tablehtml = array("&#x00c7;", "&#x00fc;", "&#x00e9;", "&#x00e2;", "&#x00e4;",
		"&#x00e0;", "&#x00e5;", "&#x00e7;", "&#x00ea;", "&#x00eb;", "&#x00e8;",
		"&#x00ef;", "&#x00ee;", "&#x00ec;", "&#x00c4;", "&#x00c5;", "&#x00c9;",
		"&#x00e6;", "&#x00c6;", "&#x00f4;", "&#x00f6;", "&#x00f2;", "&#x00fb;",
		"&#x00f9;", "&#x00ff;", "&#x00d6;", "&#x00dc;", "&#x00a2;", "&#x00a3;",
		"&#x00a5;", "&#x20a7;", "&#x0192;", "&#x00e1;", "&#x00ed;", "&#x00f3;",
		"&#x00fa;", "&#x00f1;", "&#x00d1;", "&#x00aa;", "&#x00ba;", "&#x00bf;",
		"&#x2310;", "&#x00ac;", "&#x00bd;", "&#x00bc;", "&#x00a1;", "&#x00ab;",
		"&#x00bb;", "&#x2591;", "&#x2592;", "&#x2593;", "&#x2502;", "&#x2524;",
		"&#x2561;", "&#x2562;", "&#x2556;", "&#x2555;", "&#x2563;", "&#x2551;",
		"&#x2557;", "&#x255d;", "&#x255c;", "&#x255b;", "&#x2510;", "&#x2514;",
		"&#x2534;", "&#x252c;", "&#x251c;", "&#x2500;", "&#x253c;", "&#x255e;",
		"&#x255f;", "&#x255a;", "&#x2554;", "&#x2569;", "&#x2566;", "&#x2560;",
		"&#x2550;", "&#x256c;", "&#x2567;", "&#x2568;", "&#x2564;", "&#x2565;",
		"&#x2559;", "&#x2558;", "&#x2552;", "&#x2553;", "&#x256b;", "&#x256a;",
		"&#x2518;", "&#x250c;", "&#x2588;", "&#x2584;", "&#x258c;", "&#x2590;",
		"&#x2580;", "&#x03b1;", "&#x00df;", "&#x0393;", "&#x03c0;", "&#x03a3;",
		"&#x03c3;", "&#x03bc;", "&#x03c4;", "&#x03a6;", "&#x0398;", "&#x03a9;",
		"&#x03b4;", "&#x221e;", "&#x03c6;", "&#x03b5;", "&#x2229;", "&#x2261;",
		"&#x00b1;", "&#x2265;", "&#x2264;", "&#x2320;", "&#x2321;", "&#x00f7;",
		"&#x2248;", "&#x00b0;", "&#x2219;", "&#x00b7;", "&#x221a;", "&#x207f;",
		"&#x00b2;", "&#x25a0;", "&#x00a0;");
	$s = htmlspecialchars($ibm_437);


// 0-9, 11-12, 14-31, 127 (decimalt)
	$control = array("\000", "\001", "\002", "\003", "\004", "\005", "\006", "\007",
		"\010", "\011", /* "\012", */ "\013", "\014", /* "\015", */ "\016", "\017",
		"\020", "\021", "\022", "\023", "\024", "\025", "\026", "\027",
		"\030", "\031", "\032", "\033", "\034", "\035", "\036", "\037",
		"\177");

	/* Code control characters to control pictures.
	  http://www.unicode.org/charts/PDF/U2400.pdf
	  (This is somewhat the Right Thing, but looks crappy with Courier New.)
	  $controlpict = array("&#x2423;","&#x2404;");
	  $s = str_replace($control,$controlpict,$s); */

// replace control chars with space - feel free to fix the regexp smile.gif
	/* echo "[a\\x00-\\x1F]";
	  //$s = preg_replace("/[ \\x00-\\x1F]/", " ", $s);
	  $s = preg_replace("/[ \000-\037]/", " ", $s); */
	$s = str_replace($control, " ", $s);




	if ($swedishmagic) {
		$s = str_replace("\345", "\206", $s);
		$s = str_replace("\344", "\204", $s);
		$s = str_replace("\366", "\224", $s);
// $s = str_replace("\304","\216",$s);
//$s = "[ -~]\\xC4[a-za-z]";
// couldn't get ^ and $ to work, even through I read the man-pages,
// i'm probably too tired and too unfamiliar with posix regexps right now.
		$s = preg_replace("/([ -~])\305([ -~])/", "\\1\217\\2", $s);
		$s = preg_replace("/([ -~])\304([ -~])/", "\\1\216\\2", $s);
		$s = preg_replace("/([ -~])\326([ -~])/", "\\1\231\\2", $s);

		$s = str_replace("\311", "\220", $s); //
		$s = str_replace("\351", "\202", $s); //
	}

	$s = str_replace($table437, $tablehtml, $s);
	return $s;
}

//Tooltip container for hot movie, classic movie, etc
function create_tooltip_container($id_content_arr, $width = 400) {
	if (count($id_content_arr)) {
		$result = "<div id=\"tooltipPool\" style=\"display: none\">";
		foreach ($id_content_arr as $id_content_arr_each) {
			$result .= "<div id=\"" . $id_content_arr_each['id'] . "\">" . $id_content_arr_each['content'] . "</div>";
		}
		$result .= "</div>";
		print($result);
	}
}

function getimdb($imdb_id, $cache_stamp, $mode = 'minor') {
	global $lang_functions;
	global $showextinfo;
	$thenumbers = $imdb_id;
	$movie = new imdb($thenumbers);
	$movieid = $thenumbers;
	$movie->setid($movieid);

	$target = array('Title');
	switch ($movie->cachestate($target)) {
		case "0": //cache is not ready
			{
				return false;
				break;
			}
		case "1": //normal
			{
				$title = $movie->title();
				$year = $movie->year();
				$country = $movie->country();
				$countries = "";
				$temp = "";
				for ($i = 0; $i < count($country); $i++) {
					$temp .="$country[$i], ";
				}
				$countries = rtrim(trim($temp), ",");

				$director = $movie->director();
				$director_or_creator = "";
				$temp = "";
				$temp .= $director;
				$director_or_creator = "<strong><font color=\"DarkRed\">" . $lang_functions['text_director'] . ": </font></strong>" . rtrim(trim($temp), ",");
				$cast = $movie->cast();
				$temp = "";
				$temp .= $cast;
				$casts = rtrim(trim($temp), ",");
				$gen = $movie->genre();
				$genres = $gen[0] . (count($gen) > 1 ? ", " . $gen[1] : ""); //get first two genres;
				$rating = $movie->rating();
				$votes = $movie->votes();
				if ($votes)
					$imdbrating = "<b>" . $rating . "</b>/10 (" . $votes . $lang_functions['text_votes'] . ")";
				else
					$imdbrating = $lang_functions['text_awaiting_five_votes'];

				switch ($mode) {
					case 'minor' : {
							$autodata = "<font class=\"big\"><b>" . $title . "</b></font> (" . $year . ") <br /><strong><font color=\"DarkRed\">" . $lang_functions['text_imdb'] . ": </font></strong>" . $imdbrating . " <strong><font color=\"DarkRed\">" . $lang_functions['text_country'] . ": </font></strong>" . $countries . " <strong><font color=\"DarkRed\">" . $lang_functions['text_genres'] . ": </font></strong>" . $genres . "<br />" . $director_or_creator . "<strong><font color=\"DarkRed\"> " . $lang_functions['text_starring'] . ": </font></strong>" . $casts . "<br />";
							break;
						}
					case 'median': {
							if (($photo_url = $movie->photo_localurl() ) != FALSE)
								$smallth = "<img src=\"" . $photo_url . "\" width=\"105\" alt=\"poster\" />";
							else
								$smallth = "";
							$runtime = $movie->runtime();
							$language = $movie->language();
							$plots = "";
							$plotoutline = $movie->plotoutline(); //get plot from title page
							$plots .= "<font color=\"DarkRed\">*</font> " . strip_tags($plotoutline, '<br /><i>');
							$plots = mb_substr($plots, 0, 300, "UTF-8") . (mb_strlen($plots, "UTF-8") > 300 ? " ..." : "" );
							$plots .= (strpos($plots, "<i>") == true && strpos($plots, "</i>") == false ? "</i>" : ""); //sometimes <i> is open and not ended because of mb_substr;
							$plots = "<font class=\"small\">" . $plots . "</font>";
							$autodata = "<table style=\"background-color: transparent;\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\">" . ($smallth ? "<td class=\"clear\" valign=\"top\" align=\"right\">$smallth</td>" : "") . "<td class=\"clear\" valign=\"top\" align=\"left\"><table style=\"background-color: transparent;\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\" width=\"350\"><tr><td class=\"clear\" colspan=\"2\"><img class=\"imdb\" src=\"pic/trans.gif\" alt=\"imdb\" /> <font class=\"big\"><b>" . $title . "</b></font> (" . $year . ") </td></tr><tr><td class=\"clear\"><strong><font color=\"DarkRed\">" . $lang_functions['text_imdb'] . ": </font></strong>" . $imdbrating . "</td>" . ( $runtime ? "<td class=\"clear\"><strong><font color=\"DarkRed\">" . $lang_functions['text_runtime'] . ": </font></strong>" . $runtime . "</td>" : "<td class=\"clear\"></td>") . "</tr><tr><td class=\"clear\"><strong><font color=\"DarkRed\">" . $lang_functions['text_country'] . ": </font></strong>" . $countries . "</td>" . ( $language ? "<td class=\"clear\"><strong><font color=\"DarkRed\">" . $lang_functions['text_language'] . ": </font></strong>" . $language . "</td>" : "<td class=\"clear\"></td>") . "</tr><tr><td class=\"clear\">" . $director_or_creator . "</td><td class=\"clear\"><strong><font color=\"DarkRed\">" . $lang_functions['text_genres'] . ": </font></strong>" . $genres . "</td></tr><tr><td class=\"clear\" colspan=\"2\"><strong><font color=\"DarkRed\">" . $lang_functions['text_starring'] . ": </font></strong>" . $casts . "</td></tr>" . ( $plots ? "<tr><td class=\"clear\" colspan=\"2\">" . $plots . "</td></tr>" : "") . "</table></td></table>";
							break;
						}
				}
				return $autodata;
			}
		case "2" : {
				return false;
				break;
			}
		case "3" : {
				return false;
				break;
			}
	}
}

function quickreply($formname, $taname, $submit) {
	print("<textarea name='" . $taname . "' id=\"replaytext\" cols=\"100\" rows=\"8\" style=\"width: 450px\" onkeydown=\"ctrlenter(event,'compose','qr')\"></textarea><br /><br />");
	print(smile_row($formname, $taname));
	print("<br /><input type=\"submit\" id=\"qr\" class=\"btn\" value=\"" . $submit . "\" />");
}

function smile_row($formname, $taname) {
	$smilerow = "<div align=\"center\">";
	for ($i = 1; $i <= 76; $i++) {
		$quickSmilesNumbers = array($i);
		foreach ($quickSmilesNumbers as $smilyNumber) {
			$smilerow .= getSmileIt($formname, $taname, $smilyNumber);
		}
	}
	$smilerow .= "</div>";
	return $smilerow;
}

function getSmileIt($formname, $taname, $smilyNumber) {
	return "<a href=\"javascript: SmileIT('[em$smilyNumber]','" . $formname . "','" . $taname . "')\"  onmouseover=\"domTT_activate(this, event, 'content', '" . htmlspecialchars("<table><tr><td><img style=\"width:128px;height:128px;padding-bottom:auto;\" src=\'pic/smilies/$smilyNumber.png\' alt=\'\' /></td></tr></table>") . "', 'trail', false, 'delay', 0,'lifetime',10000,'styleClass','smilies','maxWidth', 400);\"><img style=\"width:32px;height:32px;padding-bottom:auto;\" src=\"pic/smilies/$smilyNumber.png\" alt=\"\" /></a>";
}

function classlist($selectname, $maxclass, $selected, $minClass = 1) {
	$list = "<select name=\"" . $selectname . "\">";
	for ($i = $minClass; $i <= $maxclass; $i++)
		$list .= "<option value=\"" . $i . "\"" . ($selected == $i ? " selected=\"selected\"" : "") . ">" . get_user_class_name($i, false, false, true) . "</option>\n";
	$list .= "</select>";
	return $list;
}

function permissiondenied() {
	global $lang_functions;
	stderr($lang_functions['std_error'], $lang_functions['std_permission_denied']);
}

function gettime($time, $withago = true, $twoline = false, $forceago = false, $oneunit = false, $isfuturetime = false) {
	global $lang_functions, $CURUSER;
	if ($CURUSER['timetype'] != 'timealive' && !$forceago) {
		$newtime = $time;
		if ($twoline) {
			$newtime = str_replace(" ", "<br />", $newtime);
		}
	} else {
		$timestamp = strtotime($time);
		if ($isfuturetime && $timestamp < TIMENOW)
			$newtime = false;
		else {
			$newtime = get_elapsed_time($timestamp, $oneunit) . ($withago ? $lang_functions['text_ago'] : "");
			if ($twoline) {
				$newtime = str_replace("&nbsp;", "<br />", $newtime);
			} elseif ($oneunit) {
				if ($length = strpos($newtime, "&nbsp;"))
					$newtime = substr($newtime, 0, $length);
			} else
				$newtime = str_replace("&nbsp;", $lang_functions['text_space'], $newtime);
			$newtime = "<span title=\"" . $time . "\">" . $newtime . "</span>";
		}
	}
	return $newtime;
}

function get_forum_pic_folder() {
	global $CURLANGDIR;
	return "pic/forum_pic/" . $CURLANGDIR;
}

function get_category_icon_row($typeid) {
	global $Cache;
	static $rows;
	if (!$typeid) {
		$typeid = 1;
	}
	if (!$rows && !$rows = $Cache->get_value('category_icon_content')) {
		$rows = array();
		$res = sql_query("SELECT * FROM caticons ORDER BY id ASC");
		while ($row = mysql_fetch_array($res)) {
			$rows[$row['id']] = $row;
		}
		$Cache->cache_value('category_icon_content', $rows, 156400);
	}
	return $rows[$typeid];
}

function get_category_row($catid = NULL) {
	global $Cache;
	static $rows;
	if (!$rows && !$rows = $Cache->get_value('category_content')) {
		$res = sql_query("SELECT categories.*, searchbox.name AS catmodename FROM categories LEFT JOIN searchbox ON categories.mode=searchbox.id");
		while ($row = mysql_fetch_array($res)) {
			$rows[$row['id']] = $row;
		}
		$Cache->cache_value('category_content', $rows, 126400);
	}
	if ($catid) {
		return $rows[$catid];
	} else {
		return $rows;
	}
}

function get_second_icon($row, $catimgurl) { //for CHDBits
	global $CURUSER, $Cache;
	$source = $row['source'];
	$medium = $row['medium'];
	$codec = $row['codec'];
	$standard = $row['standard'];
	$processing = $row['processing'];
	$team = $row['team'];
	$audiocodec = $row['audiocodec'];
	if (!$sirow = $Cache->get_value('secondicon_' . $source . '_' . $medium . '_' . $codec . '_' . $standard . '_' . $processing . '_' . $team . '_' . $audiocodec . '_content')) {
		$res = sql_query("SELECT * FROM secondicons WHERE (source = " . sqlesc($source) . " OR source=0) AND (medium = " . sqlesc($medium) . " OR medium=0) AND (codec = " . sqlesc($codec) . " OR codec = 0) AND (standard = " . sqlesc($standard) . " OR standard = 0) AND (processing = " . sqlesc($processing) . " OR processing = 0) AND (team = " . sqlesc($team) . " OR team = 0) AND (audiocodec = " . sqlesc($audiocodec) . " OR audiocodec = 0) LIMIT 1");
		$sirow = mysql_fetch_array($res);
		if (!$sirow)
			$sirow = 'not allowed';
		$Cache->cache_value('secondicon_' . $source . '_' . $medium . '_' . $codec . '_' . $standard . '_' . $processing . '_' . $team . '_' . $audiocodec . '_content', $sirow, 116400);
	}
	$catimgurl = get_cat_folder($row['category']);
	if ($sirow == 'not allowed')
		return "<img src=\"pic/cattrans.gif\" style=\"background-image: url(pic/" . $catimgurl . "additional/notallowed.png);\" alt=\"" . $sirow["name"] . "\" alt=\"Not Allowed\" />";
	else {
		return "<img" . ($sirow['class_name'] ? " class=\"" . $sirow['class_name'] . "\"" : "") . " src=\"pic/cattrans.gif\" style=\"background-image: url(pic/" . $catimgurl . "additional/" . $sirow['image'] . ");\" alt=\"" . $sirow["name"] . "\" title=\"" . $sirow['name'] . "\" />";
	}
}

function get_torrent_bg_color($promotion = 1) {
	global $CURUSER;
	if ($CURUSER['appendpromotion'] == 'highlight') {
		$global_promotion_state = get_global_sp_state();
		if ($global_promotion_state == 1) {
			if ($promotion == 1)
				$sphighlight = "";
			elseif ($promotion == 2)
				$sphighlight = " class='free_bg'";
			elseif ($promotion == 3)
				$sphighlight = " class='twoup_bg'";
			elseif ($promotion == 4)
				$sphighlight = " class='twoupfree_bg'";
			elseif ($promotion == 5)
				$sphighlight = " class='halfdown_bg'";
			elseif ($promotion == 6)
				$sphighlight = " class='twouphalfdown_bg'";
			elseif ($promotion == 7)
				$sphighlight = " class='thirtypercentdown_bg'";
			else
				$sphighlight = "";
		}
		elseif ($global_promotion_state == 2)
			$sphighlight = " class='free_bg'";
		elseif ($global_promotion_state == 3)
			$sphighlight = " class='twoup_bg'";
		elseif ($global_promotion_state == 4)
			$sphighlight = " class='twoupfree_bg'";
		elseif ($global_promotion_state == 5)
			$sphighlight = " class='halfdown_bg'";
		elseif ($global_promotion_state == 6)
			$sphighlight = " class='twouphalfdown_bg'";
		elseif ($global_promotion_state == 7)
			$sphighlight = " class='thirtypercentdown_bg'";
		else
			$sphighlight = "";
	} else
		$sphighlight = "";
	return $sphighlight;
}

function get_torrent_promotion_append($promotion = 1, $forcemode = "", $showtimeleft = false, $added = "", $promotionTimeType = 0, $promotionUntil = '') {
	global $CURUSER, $lang_functions;
	global $expirehalfleech_torrent, $expirefree_torrent, $expiretwoup_torrent, $expiretwoupfree_torrent, $expiretwouphalfleech_torrent, $expirethirtypercentleech_torrent;

	$sp_torrent = "";
	$onmouseover = "";
	$timeout = 0;
	if (get_global_sp_state() == 1) {
		$futuretime = strtotime($added);
		if ($added == "0000-00-00 00:00:00" || $added == "")
			$timeout = 0;
		else
			$timeout = gettime(date("Y-m-d H:i:s", $futuretime), false, false, true, false, true);
		if ($promotion == 1)
			return "";
		$onmouseover = "$timeout";
	}
	if (($CURUSER['appendpromotion'] == 'word' && $forcemode == "" ) || $forcemode == 'word') {
		if ($timeout)
			$onmouseover = "[" . $lang_functions['text_will_end_in'] . $onmouseover . "]";
		if (($promotion == 2 && get_global_sp_state() == 1) || get_global_sp_state() == 2) {
			$sp_torrent = " <b>[<font class='free' >" . $lang_functions['text_free'] . "</font>]</b>";
		} elseif (($promotion == 3 && get_global_sp_state() == 1) || get_global_sp_state() == 3) {
			$sp_torrent = " <b>[<font class='twoup' >" . $lang_functions['text_two_times_up'] . "</font>]</b>";
		} elseif (($promotion == 4 && get_global_sp_state() == 1) || get_global_sp_state() == 4) {
			$sp_torrent = " <b>[<font class='twoupfree' >" . $lang_functions['text_free_two_times_up'] . "</font>]</b>";
		} elseif (($promotion == 5 && get_global_sp_state() == 1) || get_global_sp_state() == 5) {
			$sp_torrent = " <b>[<font class='halfdown' >" . $lang_functions['text_half_down'] . "</font>]</b>";
		} elseif (($promotion == 6 && get_global_sp_state() == 1) || get_global_sp_state() == 6) {
			$sp_torrent = " <b>[<font class='twouphalfdown' >" . $lang_functions['text_half_down_two_up'] . "</font>]</b>";
		} elseif (($promotion == 7 && get_global_sp_state() == 1) || get_global_sp_state() == 7) {
			$sp_torrent = " <b>[<font class='thirtypercent' >" . $lang_functions['text_thirty_percent_down'] . "</font>]</b>";
		}
	} elseif (($CURUSER['appendpromotion'] == 'icon' && $forcemode == "") || $forcemode == 'icon') {
		if ($timeout)
			$onmouseover = "[" . $lang_functions['text_will_end_in'] . $onmouseover . "]";
		if (($promotion == 2 && get_global_sp_state() == 1) || get_global_sp_state() == 2)
			$sp_torrent = " <img class=\"pro_free\" src=\"pic/trans.gif\" alt=\"Free\" title=\"" . $lang_functions['text_free'] . "\"/>";
		elseif (($promotion == 3 && get_global_sp_state() == 1) || get_global_sp_state() == 3)
			$sp_torrent = " <img class=\"pro_2up\" src=\"pic/trans.gif\" alt=\"2x\" title=\"" . $lang_functions['text_two_times_up'] . "\"/>";
		elseif (($promotion == 4 && get_global_sp_state() == 1) || get_global_sp_state() == 4)
			$sp_torrent = " <img class=\"pro_free2up\" src=\"pic/trans.gif\" alt=\"2xFree\" title=\"" . $lang_functions['text_free_two_times_up'] . "\"/>";
		elseif (($promotion == 5 && get_global_sp_state() == 1) || get_global_sp_state() == 5)
			$sp_torrent = " <img class=\"pro_50pctdown\" src=\"pic/trans.gif\" alt=\"50%\" title=\"" . $lang_functions['text_half_down'] . "\"/>";
		elseif (($promotion == 6 && get_global_sp_state() == 1) || get_global_sp_state() == 6)
			$sp_torrent = " <img class=\"pro_50pctdown2up\" src=\"pic/trans.gif\" alt=\"2x50%\" title=\"" . $lang_functions['text_half_down_two_up'] . "\"/>";
		elseif (($promotion == 7 && get_global_sp_state() == 1) || get_global_sp_state() == 7)
			$sp_torrent = " <img class=\"pro_30pctdown\" src=\"pic/trans.gif\" alt=\"30%\" title=\"" . $lang_functions['text_thirty_percent_down'] . "\"/>";
	}
	if ($timeout) {
		$sp_torrent = $sp_torrent . " <b>" . $onmouseover . "</b>";
		$sp_torrent = "<font color=\"#888888\">" . $sp_torrent . "</font>";
	}
	return $sp_torrent;
}

function get_user_id_from_name($username) {
	global $lang_functions;
	$res = sql_query("SELECT id FROM users WHERE LOWER(username) = LOWER(" . sqlesc($username) . ")");
	$arr = mysql_fetch_array($res);
	if (!$arr) {
		stderr($lang_functions['std_error'], $lang_functions['std_no_user_named'] . "'" . $username . "'");
	} else
		return $arr['id'];
}

function get_user_name_from_id($userid) {
	global $lang_functions;
	$res = sql_query("SELECT username FROM users WHERE LOWER(id) = LOWER(" . sqlesc($userid) . ")");
	$arr = mysql_fetch_array($res);
	if (!$arr) {
		stderr($lang_functions['std_error'], $lang_functions['std_no_user_named'] . "'" . $userid . "'");
	} else
		return $arr['username'];
}

function is_forum_moderator($id, $in = 'post') {
	global $CURUSER;
	switch ($in) {
		case 'post': {
				$res = sql_query("SELECT topicid FROM posts WHERE id=$id") or sqlerr(__FILE__, __LINE__);
				if ($arr = mysql_fetch_array($res)) {
					if (is_forum_moderator($arr['topicid'], 'topic'))
						return true;
				}
				return false;
				break;
			}
		case 'topic': {
				$modcount = sql_query("SELECT COUNT(forummods.userid) FROM forummods LEFT JOIN topics ON forummods.forumid = topics.forumid WHERE topics.id=$id AND forummods.userid=" . sqlesc($CURUSER['id'])) or sqlerr(__FILE__, __LINE__);
				$arr = mysql_fetch_array($modcount);
				if ($arr[0])
					return true;
				else
					return false;
				break;
			}
		case 'forum': {
				$modcount = get_row_count("forummods", "WHERE forumid=$id AND userid=" . sqlesc($CURUSER['id']));
				if ($modcount)
					return true;
				else
					return false;
				break;
			}
		default: {
				return false;
			}
	}
}

function get_guest_lang_id() {
	global $CURLANGDIR;
	$langfolder = $CURLANGDIR;
	$res = sql_query("SELECT id FROM language WHERE site_lang_folder=" . sqlesc($langfolder) . " AND site_lang=1");
	$row = mysql_fetch_array($res);
	if ($row) {
		return $row['id'];
	} else
		return 6; //return English
}

function set_forum_moderators($name, $forumid, $limit = 3) {
	$name = rtrim(trim($name), ",");
	$users = explode(",", $name);
	$userids = array();
	foreach ($users as $user) {
		$userids[] = get_user_id_from_name(trim($user));
	}
	$max = count($userids);
	sql_query("DELETE FROM forummods WHERE forumid=" . sqlesc($forumid)) or sqlerr(__FILE__, __LINE__);
	for ($i = 0; $i < $limit && $i < $max; $i++) {
		sql_query("INSERT INTO forummods (forumid, userid) VALUES (" . sqlesc($forumid) . "," . sqlesc($userids[$i]) . ")") or sqlerr(__FILE__, __LINE__);
	}
}

function get_plain_username($id) {
	$row = get_user_row($id);
	if ($row)
		$username = $row['username'];
	else
		$username = "";
	return $username;
}

function get_searchbox_value($mode = 1, $item = 'showsubcat') {
	global $Cache;
	static $rows;
	if (!$rows && !$rows = $Cache->get_value('searchbox_content')) {
		$rows = array();
		$res = sql_query("SELECT * FROM searchbox ORDER BY id ASC");
		while ($row = mysql_fetch_array($res)) {
			$rows[$row['id']] = $row;
		}
		$Cache->cache_value('searchbox_content', $rows, 100500);
	}
	return $rows[$mode][$item];
}

function get_ratio($userid, $html = true) {
	global $lang_functions;
	$row = get_user_row($userid);
	$uped = $row['uploaded'];
	$downed = $row['downloaded'];
	if ($html == true) {
		if ($downed > 0) {
			$ratio = $uped / $downed;
			$color = get_ratio_color($ratio);
			$ratio = number_format($ratio, 3);

			if ($color)
				$ratio = "<font color=\"" . $color . "\">" . $ratio . "</font>";
		}
		elseif ($uped > 0)
			$ratio = $lang_functions['text_inf'];
		else
			$ratio = "---";
	}
	else {
		if ($downed > 0) {
			$ratio = $uped / $downed;
		} else
			$ratio = 1;
	}
	return $ratio;
}

function add_s($num, $es = false) {
	global $lang_functions;
	return ($num > 1 ? ($es ? $lang_functions['text_es'] : $lang_functions['text_s']) : "");
}

function is_or_are($num) {
	global $lang_functions;
	return ($num > 1 ? $lang_functions['text_are'] : $lang_functions['text_is']);
}

function getmicrotime() {
	list($usec, $sec) = explode(" ", microtime());
	return ((float) $usec + (float) $sec);
}

function user_can_upload($where = "torrents") {
	global $CURUSER, $upload_class, $enablespecial, $uploadspecial_class;

	if ($CURUSER["uploadpos"] != 'yes')
		return false;
	if ($where == "torrents") {
		if (get_user_class() >= $upload_class)
			return true;
		if (get_if_restricted_is_open())
			return true;
	}
	return false;
}

function torrent_selection($name, $selname, $listname, $selectedid = 0) {
	global $lang_functions;
	$selection = "<b>" . $name . "</b>&nbsp;<select id=\"" . $selname . "\" name=\"" . $selname . "\">\n<option value=\"0\">" . $lang_functions['select_choose_one'] . "</option>\n";
	$listarray = searchbox_item_list($listname);
	foreach ($listarray as $row)
		$selection .= "<option value=\"" . $row["id"] . "\"" . ($row["id"] == $selectedid ? " selected=\"selected\"" : "") . ">" . htmlspecialchars($row["name"]) . "</option>\n";
	$selection .= "</select>&nbsp;&nbsp;&nbsp;\n";
	return $selection;
}

function get_hl_color($color = 0) {
	switch ($color) {
		case 0: return false;
		case 1: return "Black";
		case 2: return "Sienna";
		case 3: return "DarkOliveGreen";
		case 4: return "DarkGreen";
		case 5: return "DarkSlateBlue";
		case 6: return "Navy";
		case 7: return "Indigo";
		case 8: return "DarkSlateGray";
		case 9: return "DarkRed";
		case 10: return "DarkOrange";
		case 11: return "Olive";
		case 12: return "Green";
		case 13: return "Teal";
		case 14: return "Blue";
		case 15: return "SlateGray";
		case 16: return "DimGray";
		case 17: return "Red";
		case 18: return "SandyBrown";
		case 19: return "YellowGreen";
		case 20: return "SeaGreen";
		case 21: return "MediumTurquoise";
		case 22: return "RoyalBlue";
		case 23: return "Purple";
		case 24: return "Gray";
		case 25: return "Magenta";
		case 26: return "Orange";
		case 27: return "Yellow";
		case 28: return "Lime";
		case 29: return "Cyan";
		case 30: return "DeepSkyBlue";
		case 31: return "DarkOrchid";
		case 32: return "Silver";
		case 33: return "Pink";
		case 34: return "Wheat";
		case 35: return "LemonChiffon";
		case 36: return "PaleGreen";
		case 37: return "PaleTurquoise";
		case 38: return "LightBlue";
		case 39: return "Plum";
		case 40: return "White";
		default: return false;
	}
}

function get_forum_moderators($forumid, $plaintext = true) {
	global $Cache;
	static $moderatorsArray;

	if (!$moderatorsArray && !$moderatorsArray = $Cache->get_value('forum_moderator_array')) {
		$moderatorsArray = array();
		$res = sql_query("SELECT forumid, userid FROM forummods ORDER BY forumid ASC") or sqlerr(__FILE__, __LINE__);
		while ($row = mysql_fetch_array($res)) {
			$moderatorsArray[$row['forumid']][] = $row['userid'];
		}
		$Cache->cache_value('forum_moderator_array', $moderatorsArray, 86200);
	}
	$ret = (array) $moderatorsArray[$forumid];

	$moderators = "";
	foreach ($ret as $userid) {
		if ($plaintext)
			$moderators .= get_plain_username($userid) . ", ";
		else
			$moderators .= get_username($userid) . ", ";
	}
	$moderators = rtrim(trim($moderators), ",");
	return $moderators;
}

function key_shortcut($page = 1, $pages = 1) {
	$currentpage = "var currentpage=" . $page . ";";
	$maxpage = "var maxpage=" . $pages . ";";
	$key_shortcut_block = "\n<script type=\"text/javascript\">\n//<![CDATA[\n" . $maxpage . "\n" . $currentpage . "\n//]]>\n</script>\n";
	return $key_shortcut_block;
}

function promotion_selection($selected = 0, $hide = 0) {
	global $lang_functions, $ratioless;
	$selection = "";
	if ($ratioless == 'no') {
		if ($hide != 1)
			$selection .= "<option value=\"1\"" . ($selected == 1 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_normal'] . "</option>";
		if ($hide != 2)
			$selection .= "<option value=\"2\"" . ($selected == 2 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_free'] . "</option>";
		if ($hide != 3)
			$selection .= "<option value=\"3\"" . ($selected == 3 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_two_times_up'] . "</option>";
		if ($hide != 4)
			$selection .= "<option value=\"4\"" . ($selected == 4 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_free_two_times_up'] . "</option>";
		if ($hide != 5)
			$selection .= "<option value=\"5\"" . ($selected == 5 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_half_down'] . "</option>";
		if ($hide != 6)
			$selection .= "<option value=\"6\"" . ($selected == 6 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_half_down_two_up'] . "</option>";
		if ($hide != 7)
			$selection .= "<option value=\"7\"" . ($selected == 7 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_thirty_percent_down'] . "</option>";
	} else {
		if ($hide != 1)
			$selection .= "<option value=\"1\"" . ($selected == 1 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_normal'] . "</option>";
		if ($hide != 3)
			$selection .= "<option value=\"3\"" . ($selected == 3 ? " selected=\"selected\"" : "") . ">" . $lang_functions['text_two_times_up'] . "</option>";
	}
	return $selection;
}

function get_post_row($postid) {
	global $Cache;
	if (!$row = $Cache->get_value('post_' . $postid . '_content')) {
		$res = sql_query("SELECT * FROM posts WHERE id=" . sqlesc($postid) . " LIMIT 1") or sqlerr(__FILE__, __LINE__);
		$row = mysql_fetch_array($res);
		$Cache->cache_value('post_' . $postid . '_content', $row, 7200);
	}
	if (!$row)
		return false;
	else
		return $row;
}

function get_country_row($id) {
	global $Cache;
	if (!$row = $Cache->get_value('country_' . $id . '_content')) {
		$res = sql_query("SELECT * FROM countries WHERE id=" . sqlesc($id) . " LIMIT 1") or sqlerr(__FILE__, __LINE__);
		$row = mysql_fetch_array($res);
		$Cache->cache_value('country_' . $id . '_content', $row, 86400);
	}
	if (!$row)
		return false;
	else
		return $row;
}

function get_downloadspeed_row($id) {
	global $Cache;
	if (!$row = $Cache->get_value('downloadspeed_' . $id . '_content')) {
		$res = sql_query("SELECT * FROM downloadspeed WHERE id=" . sqlesc($id) . " LIMIT 1") or sqlerr(__FILE__, __LINE__);
		$row = mysql_fetch_array($res);
		$Cache->cache_value('downloadspeed_' . $id . '_content', $row, 86400);
	}
	if (!$row)
		return false;
	else
		return $row;
}

function get_uploadspeed_row($id) {
	global $Cache;
	if (!$row = $Cache->get_value('uploadspeed_' . $id . '_content')) {
		$res = sql_query("SELECT * FROM uploadspeed WHERE id=" . sqlesc($id) . " LIMIT 1") or sqlerr(__FILE__, __LINE__);
		$row = mysql_fetch_array($res);
		$Cache->cache_value('uploadspeed_' . $id . '_content', $row, 86400);
	}
	if (!$row)
		return false;
	else
		return $row;
}

function get_isp_row($id) {
	global $Cache;
	if (!$row = $Cache->get_value('isp_' . $id . '_content')) {
		$res = sql_query("SELECT * FROM isp WHERE id=" . sqlesc($id) . " LIMIT 1") or sqlerr(__FILE__, __LINE__);
		$row = mysql_fetch_array($res);
		$Cache->cache_value('isp_' . $id . '_content', $row, 86400);
	}
	if (!$row)
		return false;
	else
		return $row;
}

function valid_file_name($filename) {
	$allowedchars = "abcdefghijklmnopqrstuvwxyz0123456789_./";

	$total = strlen($filename);
	for ($i = 0; $i < $total; ++$i)
		if (strpos($allowedchars, $filename[$i]) === false)
			return false;
	return true;
}

function valid_class_name($filename) {
	$allowedfirstchars = "abcdefghijklmnopqrstuvwxyz";
	$allowedchars = "abcdefghijklmnopqrstuvwxyz0123456789_";

	if (strpos($allowedfirstchars, $filename[0]) === false)
		return false;
	$total = strlen($filename);
	for ($i = 1; $i < $total; ++$i)
		if (strpos($allowedchars, $filename[$i]) === false)
			return false;
	return true;
}

function return_avatar_image($url) {
	global $CURLANGDIR;
	return "<img src=\"" . $url . "\" alt=\"avatar\" width=\"150px\" onload=\"check_avatar(this, '" . $CURLANGDIR . "');\" />";
}

function return_category_image($categoryid, $link = "") {
	static $catImg = array();
	if ($catImg[$categoryid]) {
		$catimg = $catImg[$categoryid];
	} else {
		$categoryrow = get_category_row($categoryid);
		$catimgurl = get_cat_folder($categoryid);
		$catImg[$categoryid] = $catimg = "<img" . ($categoryrow['class_name'] ? " class=\"" . $categoryrow['class_name'] . "\"" : "") . " src=\"pic/cattrans.gif\" alt=\"" . $categoryrow["name"] . "\" title=\"" . $categoryrow["name"] . "\" style=\"background-image: url(pic/" . $catimgurl . $categoryrow["image"] . "); height:60px; width:48px\" />";
	}
	if ($link) {
		$catimg = "<a href=\"" . $link . "cat=" . $categoryid . "\">" . $catimg . "</a>";
	}
	return $catimg;
}

function Clean_Sticky($id, $state, $endtime, $name) {//删除置顶标记
	if ($state != "normal" && $endtime != "0000-00-00 00:00:00") {
		if ($endtime < date("Y-m-d H:i:s", time())) {
			sql_query("UPDATE torrents SET bumpoff = 'no', pos_state = 'normal' WHERE id = " . sqlesc($id)) or sqlerr(__FILE__, __LINE__);
			write_log("种子： $id" . " " . "$name 因置顶时间到期而取消置顶，置顶时间到：$endtime");
			return true;
		}
	} else {
		return false;
	}
}

function Clean_Marrow($id, $state, $endtime, $name) {//删除置顶标记
	if ($state != "normal" && $endtime != "0000-00-00 00:00:00") {
		if ($endtime < date("Y-m-d H:i:s", time())) {
			sql_query("UPDATE torrents SET bumpoff = 'no', marrow = 'normal' WHERE id = " . sqlesc($id)) or sqlerr(__FILE__, __LINE__);
			write_log("种子： $id" . " " . "$name 因超级置顶时间到期而取消超级置顶，超级置顶时间到：$endtime");
			return true;
		}
	} else {
		return false;
	}
}

function Clean_Free($id, $state, $endtime, $name) {//清除促销标记
	if ($state != "1" && $endtime != "0000-00-00 00:00:00") {
		if ($endtime < date("Y-m-d H:i:s", time())) {
			sql_query("UPDATE torrents SET bumpoff = 'no', sp_state = '1' WHERE id = " . sqlesc($id)) or sqlerr(__FILE__, __LINE__);
			write_log("种子： $id" . " " . "$name 因促销时间到期而取消促销，促销时间到：$endtime");
			return true;
		}
	} else {
		return false;
	}
}

function record_op_log($op_id, $user_id, $user_name, $op, $detail) {//封禁删用户日志
	sql_query("INSERT INTO users_log (op_id, user_id, user_name, op, detail, op_time) VALUES(" . sqlesc($op_id) . "," . sqlesc($user_id) . "," . sqlesc($user_name) . "," . sqlesc($op) . "," . sqlesc($detail) . ",now())") or sqlerr(__FILE__, __LINE__);
}

function school_ip_location($ip, $detail = true) {
	$schoolip = explode(":", $ip);
	$schoolt = sprintf('%04s', strtoupper($schoolip[0])) . sprintf('%04s', strtoupper($schoolip[1])) . sprintf('%04s', strtoupper($schoolip[2])) . sprintf('%04s', strtoupper($schoolip[3]));
	$rowip = mysql_fetch_array(sql_query("SELECT country, local FROM ipv6 WHERE ipv6start <= '$schoolt' AND ipv6end >= '$schoolt'"));
	if ($detail) {
		$school = $rowip['country'] . " " . $rowip['local'];
	} else {
		$school = $rowip['country'];
	}
	return $school;
}

function quote_sub($text) {//清理引用层数
	if (strlen($text) > 50) {
		return quote_sub_math($text, strlen($text));
	} else {
		return $text;
	}
}

function quote_sub_math($text, $textlen, $start = 0, $end = 0, $in = 3) {//清理引用层数的递归
	global $starta, $enda, $ina;
	if ($textlen > 1 && $start == 0 && $end == 0)
		$end = $textlen - 1;
	$start = stripos($text, "[quote", $start);
	if ($in >= 0) {
		if ($start !== false) {
			$end = strripos(substr($text, 0, $end + 4), "[/quote]");
			if ($end !== false) {
				$starta = $start;
				$enda = $end + 8;
				quote_sub_math($text, $textlen, $start + 1, $end, $in - 1);
			}
		}
	} else {
		$ina = $in;
	}
	if ($ina < 0)
		return substr($text, 0, $starta) . "[quote][color=DimGray]......(系统自动省略)[/color][/quote]" . substr($text, $enda);
	else
		return $text;
}

function getOneCard($stuid, $cardpass) {
	$cardpass = md5(md5($cardpass) . "]+yTi#Klq46%");

	ini_set("max_execution_time", 35);
	$url = "http://ldapauth.nwsuaf.edu.cn/auth/md5auth?userid=" . $stuid . "&pwd=" . $cardpass;
	//$html = file_get_contents($url);

	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$retinfo = curl_exec($ch);
	curl_close($ch);
	if ($retinfo === false) {
		bark('连接学号认证服务器超时，请改天再试并联系管理员');
		die;
	}; //bark是takecard.php中自定义的返回提示信息的函数

	$retinfo = json_decode($retinfo, true);
	if ($retinfo['auth'] == '1')
		return true;
	else
		return false;
}

/**
 * 当删除种子时对所有下载者和做种者发送删除的消息
 *
 * @param int $id torrent id
 * @return null
 * @author SamuraiMe,2013.05.17
 */
function sendDelMsg($id, $reason = "", $mode = "recycle") {
	global $CURUSER;
	$downloaders = array();
	$seeders = array();
	$finished = array();

	if ($reason) {
		$reason = "，原因是：{$reason}";
	}
	if ($mode == "recycle") {
		$mode = "扔进回收站了";
	} else {
		$mode = "删除了";
	}

	$result1 = sql_query("SELECT name, owner FROM torrents WHERE id = $id") or sqlerr();
	$row = mysql_fetch_row($result1);
	$torrentName = $row[0];
	$owner = $row[1];

	$result2 = sql_query("SELECT userid, seeder FROM peers WHERE torrent = $id") or sqlerr();
	while ($row = mysql_fetch_row($result2)) {
		if ($row[0] != $owner && $row[0] != $CURUSER['id']) {
			if (strtolower(trim($row[1])) == "yes") {
				$seeders[] = $row[0];
			} else {
				$downloaders[] = $row[0];
			}
		}
	}

	$result3 = sql_query("SELECT userid FROM snatched WHERE torrentid = $id AND finished = 'yes'") or sqlerr();
	while ($row = mysql_fetch_row($result3)) {
		$finished[] = $row[0];
	}
	if ($mode == "扔进回收站了") {
		$torrenturll = "[url=details.php?id=$id]";
		$torrenturlr = "[/url]";
	}
	if ($owner != $CURUSER['id']) {
		sendMessage(0, $owner, "你发布的种子被$mode", "你发布的ID为 {$id} 的种子[b] $torrenturll{$torrentName}$torrenturlr [/b]被 [url=userdetails.php?id={$CURUSER['id']}]{$CURUSER['username']}[/url] $mode{$reason}");
	}
	sendGroupMessage(0, $seeders, "你正在做种的种子被$mode", "你正在做种的ID为 {$id} 的种子[b] $torrenturll{$torrentName}$torrenturlr [/b]被 [url=userdetails.php?id={$CURUSER['id']}]{$CURUSER['username']}[/url] $mode{$reason}");
	sendGroupMessage(0, $downloaders, "你正在下载的种子被$mode", "你正在下载的ID为 {$id} 的种子[b] $torrenturll{$torrentName}$torrenturlr [/b]被 [url=userdetails.php?id={$CURUSER['id']}]{$CURUSER['username']}[/url] $mode{$reason}");
	sendGroupMessage(0, $finished, "你下载完成的种子被$mode", "你下载完成的ID为 {$id} 的种子[b] $torrenturll{$torrentName}$torrenturlr [/b]被 [url=userdetails.php?id={$CURUSER['id']}]{$CURUSER['username']}[/url] $mode{$reason}");
}

/**
 * 给一组用户发送一条消息
 *
 * @param array $users 一组用户的id
 * @param string $subject 消息标题
 * @param string $messge 消息主体
 * @return null
 * @author SamuraiMe,2013.05.17
 */
function sendGroupMessage($sender, $receivers, $subject, $message) {
	foreach ($receivers as $receiver) {
		sendMessage($sender, $receiver, $subject, $message);
	}
}

//goto 为1时，打开站内信自动转向[url=]内的链接，转入一次之后失效。此功能由messages.php实现
function sendMessage($sender, $receiver, $subject, $message, $goto, $added) {
	if (!isset($added) or $added == '')
		$added = date("Y-m-d H:i:s");
	if (!$goto)
		$goto = 0;
	sql_query("INSERT INTO messages (sender, subject, receiver, msg, added, goto) VALUES ($sender, " . sqlesc($subject) . ", $receiver, " . sqlesc($message) . ", " . sqlesc($added) . ", $goto)") or sqlerr(__FILE__, __LINE__);
}

//by扬扬，用于添加新的账户历史，新记录不需要换行，之前直接使用SQL实现的未作修改
function writeModComment($id, $newModComment, $added) {
	$opid = sqlesc($opid);
	if (!isset($added))
		$added = date("Y-m-d H:i:s");
	$res = sql_query("SELECT modcomment FROM users WHERE id = $id ") or sqlerr(__FILE__, __LINE__);
	$arr = mysql_fetch_assoc($res);
	$modcomment = $added . "---" . $newModComment . "\n" . $arr['modcomment'];
	$modcomment = sqlesc($modcomment);
	sql_query("UPDATE users SET modcomment = $modcomment WHERE id = $id ") or sqlerr(__FILE__, __LINE__);
}

//用于添加魔力值记录
function writeBonusComment($id, $newLog, $added) {
	if (!isset($added))
		$added = date("Y-m-d H:i:s");
	$res = sql_query("SELECT bonuscomment FROM users WHERE id = $id ") or sqlerr(__FILE__, __LINE__);
	$arr = mysql_fetch_assoc($res);
	$log = $added . "---" . $newLog . "\n" . $arr['bonuscomment'];
	$log = sqlesc($log);
	sql_query("UPDATE users SET bonuscomment = $log WHERE id = $id ") or sqlerr(__FILE__, __LINE__);
}

//为用户添加魔力值，num可以为负数。与KPS函数功能重复。by扬扬
function addBonus($userid, $num) {
	sql_query("UPDATE users SET seedbonus = seedbonus + $num WHERE id = " . sqlesc($userid)) or sqlerr(__FILE__, __LINE__);
	/*
	  global $CURUSER;
	  if ($num < 0) {
	  if ($CURUSER['seedbonus'] + $num < 0) {
	  stderr("错误", "您的魔力值不足");
	  } else {
	  sql_query("UPDATE users SET seedbonus = seedbonus + $num WHERE id = " . sqlesc($userid)) or sqlerr(__FILE__, __LINE__);
	  }
	  } else {
	  sql_query("UPDATE users SET seedbonus = seedbonus + $num WHERE id = " . sqlesc($userid)) or sqlerr(__FILE__, __LINE__);
	  }
	 *
	 */
}

function getTorrentStatus($status) {
	switch ($status) {
		case 'recycle':
			return "回收站";
		case 'candidate':
			return "候选";
		default:
			return "正常";
	}
}

//显示二级分类图标用到的函数
function return_sec_category_image($category, $source, $link = "") {
	static $catImg = array();
	if ($catImg[$source]) {
		$catimg = $catImg[$source];
	} else {
		$categoryrow = get_sec_category_row($source);
		$catimgurl = get_cat_folder($category);
		$catImg[$source] = $catimg = "<img" . " src=\"pic/cattrans.gif\" alt=\"" . $categoryrow["name"] . "\" title=\"" . $categoryrow["name"] . "\" style=\"width:48px;height:60px;background-image: url(pic/" . $catimgurl . '/sec/' . $source . ".png);background-position: top left;\" />";
	}
	if ($link) {
		$catimg = "<a href=\"" . $link . "cat=" . $category . "&source=" . $source . "\">" . $catimg . "</a>";
	}
	return $catimg;
}

function get_sec_category_row($catid = NULL) {
	global $Cache;
	static $rows;
	if (!$rows && !$rows = $Cache->get_value('source_content')) {
		$res = sql_query("SELECT * FROM sources ") or sqlerr(__FILE__, __LINE__);
		while ($row = mysql_fetch_array($res)) {
			$rows[$row['id']] = $row;
		}
		$Cache->cache_value('source_content', $rows, 126400);
	}
	if ($catid) {
		return $rows[$catid];
	} else {
		return $rows;
	}
}

//二级分类图标结束
function at_user_message($text, $title, $type) {
	global $Cache;
	global $CURUSER;
	$goto = 1;
	if ($type == "shoutbox") {
		$type = '在首页群聊';
		$title1 = "他说：" . $text;
		$goto = 0;
	} elseif ($type == "request") {
		$type = '在求种';
	} elseif ($type == "topic") {
		$type = '在帖子';
	} else {
		$type = '可能在种子';
	}
	$subject = "你 $type $title 中被[url=userdetails.php?id=$CURUSER[id]]$CURUSER[username][/url]@了，快去看看吧\n$title1";
	preg_match_all("/\[@([^\]]+?)\]/", $text, $useridget);
	$useridget[1] = array_unique($useridget[1]);
	$sql_part = 'SELECT id FROM users WHERE username IN(';
	$sql = 'INSERT INTO messages (sender, receiver, subject, msg, added, goto) VALUES';
	if (count($useridget[1]) > 0) {
		foreach ($useridget[1] as $v)
			$sql_part .= sqlesc($v) . ',';
		$sql_part = substr($sql_part, 0, -1) . ')';
		$res = sql_query($sql_part);
		if ($res) {
			while ($row = mysql_fetch_row($res)) {
				$sql .= '(0,' . $row[0] . ',"有用户@到你了！",' . sqlesc($subject) . ', NOW(),' . $goto . '),';
			}
			$sql = substr($sql, 0, -1);
		}
		sql_query($sql);
		$Cache->delete_value('user_' . $useridget[1][$i] . '_unread_message_count');
		$Cache->delete_value('user_' . $useridget[1][$i] . '_inbox_count');
	}
}

function at_format($unstr) {
	return preg_replace("/\[@([^\]]+?)\]/", '<a name="@$1"><b>@$1</b></a>', $unstr);
}

function sendshoutbox($text, $userid, $type, $date) {
	if (!isset($userid) or $userid == '')
		$userid = 11;
	if (!isset($type) or $type == '')
		$type = 'sb';
	if (!isset($date) or $date == '')
		$date = sqlesc(time());
	sql_query("INSERT INTO shoutbox (userid, date, text, type, ip) VALUES (" . sqlesc($userid) . ", $date, " . sqlesc(RemoveXSS(trim($text))) . ", " . sqlesc($type) . ", " . sqlesc(getip()) . ")") or sqlerr(__FILE__, __LINE__);
}

function convertip($ip) {
	//IP数据文件路径
	$dat_path = 'include/qqwry.dat';
	//检查IP地址
	if (!ereg("^([0-9]{1,3}.){3}[0-9]{1,3}$", $ip)) {
		return;
	}
	//打开IP数据文件
	if (!$fd = @fopen($dat_path, 'rb')) {
		return;
	}
	//分解IP进行运算，得出整形数
	$ip = explode('.', $ip);
	$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
	//获取IP数据索引开始和结束位置
	$DataBegin = fread($fd, 4);
	$DataEnd = fread($fd, 4);
	$ipbegin = implode('', unpack('L', $DataBegin));
	if ($ipbegin < 0)
		$ipbegin += pow(2, 32);
	$ipend = implode('', unpack('L', $DataEnd));
	if ($ipend < 0)
		$ipend += pow(2, 32);
	$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
	$BeginNum = 0;
	$EndNum = $ipAllNum;
	//使用二分查找法从索引记录中搜索匹配的IP记录
	while ($ip1num > $ipNum || $ip2num < $ipNum) {
		$Middle = intval(($EndNum + $BeginNum) / 2);
		//偏移指针到索引位置读取4个字节
		fseek($fd, $ipbegin + 7 * $Middle);
		$ipData1 = fread($fd, 4);
		if (strlen($ipData1) < 4) {
			fclose($fd);
			return;
		}
		//提取出来的数据转换成长整形，如果数据是负数则加上2的32次幂
		$ip1num = implode('', unpack('L', $ipData1));
		if ($ip1num < 0)
			$ip1num += pow(2, 32);
		//提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
		if ($ip1num > $ipNum) {
			$EndNum = $Middle;
			continue;
		}
		//取完上一个索引后取下一个索引
		$DataSeek = fread($fd, 3);
		if (strlen($DataSeek) < 3) {
			fclose($fd);
			return;
		}
		$DataSeek = implode('', unpack('L', $DataSeek . chr(0)));
		fseek($fd, $DataSeek);
		$ipData2 = fread($fd, 4);
		if (strlen($ipData2) < 4) {
			fclose($fd);
			return;
		}
		$ip2num = implode('', unpack('L', $ipData2));
		if ($ip2num < 0)
			$ip2num += pow(2, 32);
		//没找到提示未知
		if ($ip2num < $ipNum) {
			if ($Middle == $BeginNum) {
				fclose($fd);
				return;
			}
			$BeginNum = $Middle;
		}
	}
	//下面的代码读晕了，没读明白，有兴趣的慢慢读
	$ipFlag = fread($fd, 1);
	if ($ipFlag == chr(1)) {
		$ipSeek = fread($fd, 3);
		if (strlen($ipSeek) < 3) {
			fclose($fd);
			return;
		}
		$ipSeek = implode('', unpack('L', $ipSeek . chr(0)));
		fseek($fd, $ipSeek);
		$ipFlag = fread($fd, 1);
	}
	if ($ipFlag == chr(2)) {
		$AddrSeek = fread($fd, 3);
		if (strlen($AddrSeek) < 3) {
			fclose($fd);
			return;
		}
		$ipFlag = fread($fd, 1);
		if ($ipFlag == chr(2)) {
			$AddrSeek2 = fread($fd, 3);
			if (strlen($AddrSeek2) < 3) {
				fclose($fd);
				return;
			}
			$AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
			fseek($fd, $AddrSeek2);
		} else {
			fseek($fd, -1, SEEK_CUR);
		}
		while (($char = fread($fd, 1)) != chr(0))
			$ipAddr2 .= $char;
		$AddrSeek = implode('', unpack('L', $AddrSeek . chr(0)));
		fseek($fd, $AddrSeek);
		while (($char = fread($fd, 1)) != chr(0))
			$ipAddr1 .= $char;
	} else {
		fseek($fd, -1, SEEK_CUR);
		while (($char = fread($fd, 1)) != chr(0))
			$ipAddr1 .= $char;
		$ipFlag = fread($fd, 1);
		if ($ipFlag == chr(2)) {
			$AddrSeek2 = fread($fd, 3);
			if (strlen($AddrSeek2) < 3) {
				fclose($fd);
				return;
			}
			$AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
			fseek($fd, $AddrSeek2);
		} else {
			fseek($fd, -1, SEEK_CUR);
		}
		while (($char = fread($fd, 1)) != chr(0)) {
			$ipAddr2 .= $char;
		}
	}
	fclose($fd);
	//最后做相应的替换操作后返回结果

	$ipAddr1 = mb_convert_encoding($ipAddr1, "utf-8", "gb2312" . ',auto');
	$ipAddr2 = mb_convert_encoding($ipAddr2, "utf-8", "gb2312" . ',auto');

	if (preg_match('/http/i', $ipAddr2)) {
		$ipAddr2 = '';
	}

	if (preg_match('/大学/i', $ipAddr1)) {
		$ipAddr2 = '';
		$ipAddr1 = preg_replace("/大学.*/is", "", $ipAddr1) . "大学";
	} elseif (preg_match('/大学/i', $ipAddr2)) {
		$ipAddr1 = '';
		$ipAddr2 = preg_replace("/大学.*/is", "", $ipAddr2) . "大学";
	}

	if (preg_match('/学院/i', $ipAddr1)) {
		$ipAddr2 = '';
		$ipAddr1 = preg_replace("/学院.*/is", "", $ipAddr1) . "学院";
	} elseif (preg_match('/学院/i', $ipAddr2)) {
		$ipAddr1 = '';
		$ipAddr2 = preg_replace("/学院.*/is", "", $ipAddr2) . "学院";
	}
	$ipaddr = str_replace(" ", "", $ipAddr1 . $ipAddr2);
	$ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
	$ipaddr = preg_replace('/^s*/is', '', $ipaddr);
	$ipaddr = preg_replace('/s*$/is', '', $ipaddr);
	if (preg_match('/http/i', $ipaddr) || $ipaddr == '') {
		return "IPV4";
	}
	return ($ipaddr);
}
